﻿#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2012, Outcoder. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2013-03-21 20:07:26Z</CreationDate>
</File>
*/
#endregion

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;

using Windows.UI.Core;

using Outcoder.Concurrency;

namespace Outcoder
{
	/// <summary>
	/// Singleton class providing the default implementation 
	/// for the <see cref="ISynchronizationContext"/>, specifically for the UI thread.
	/// </summary>
	public partial class UISynchronizationContext : ISynchronizationContext
	{
		CoreDispatcher dispatcher;
		bool initialized;

		#region Singleton implementation

		static readonly UISynchronizationContext instance = new UISynchronizationContext();

		/// <summary>
		/// Gets the singleton instance.
		/// </summary>
		/// <value>The singleton instance.</value>
		public static ISynchronizationContext Instance
		{
			get
			{
				return instance;
			}
		}

		UISynchronizationContext()
		{
			/* Intentionally left blank. */
		}

		#endregion

		public void Initialize()
		{
			EnsureInitialized();
		}

		readonly object initializationLock = new object();

		void EnsureInitialized()
		{
			if (initialized)
			{
				return;
			}

			lock (initializationLock)
			{
				if (initialized)
				{
					return;
				}

				try
				{
					dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
#if !NETFX_CORE
					context = new DispatcherSynchronizationContext(dispatcher);
#endif

				}
				catch (InvalidOperationException ex)
				{
					/* TODO: Make localizable resource. */
					throw new ConcurrencyException("Initialize called from non-UI thread.", ex);
				}

				initialized = dispatcher != null;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public void Initialize(CoreDispatcher dispatcher)
		{
			ArgumentValidator.AssertNotNull(dispatcher, "dispatcher");
			lock (initializationLock)
			{
				this.dispatcher = dispatcher;
#if !NETFX_CORE
				context = new DispatcherSynchronizationContext(dispatcher);
#endif
				initialized = dispatcher != null;
			}
		}

		public void InvokeWithoutBlocking(SendOrPostCallback callback, object state,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(callback, "callback");
			EnsureInitialized();

#if NETFX_CORE
#pragma warning disable 4014
			dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => callback(state));
#pragma warning restore 4014
#else
			context.Post(callback, state);
#endif
		}

		public void InvokeWithoutBlocking(Action action,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(action, "action");
			EnsureInitialized();

#if NETFX_CORE
#pragma warning disable 4014
			dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action());
#pragma warning restore 4014
#else
			dispatcher.BeginInvoke(action);
#endif
		}

#if NETFX_CORE
		public async void InvokeAndBlockUntilCompletion(SendOrPostCallback callback, object state,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(callback, "callback");
			EnsureInitialized();
			await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => callback(state));
		}
#else
		public void InvokeAndBlockUntilCompletion(SendOrPostCallback callback, object state,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(callback, "callback");
			EnsureInitialized();
			context.Send(callback, state);
		}
#endif

#if NETFX_CORE
		public async void InvokeAndBlockUntilCompletion(Action action,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(action, "action");
			EnsureInitialized();

			if (dispatcher.HasThreadAccess)
			{
				action();
			}
			else
			{
				await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action());
			}
		}
#else
		public void InvokeAndBlockUntilCompletion(Action action,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(action, "action");
			EnsureInitialized();

			if (dispatcher.CheckAccess())
			{
				action();
			}
			else
			{
				context.Send(delegate { action(); }, null);
			}
		}
#endif

		public void InvokeIfRequired(Action action,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			if (InvokeRequired)
			{
#pragma warning disable 4014
				dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action());
#pragma warning restore 4014
			}
			else
			{
				action();
			}
		}

		public bool InvokeRequired
		{
			get
			{
				EnsureInitialized();
				return !dispatcher.HasThreadAccess;
			}
		}
	}
}
